﻿using System.Configuration;
using System.IO;
using UpdaterComponents.Common;

namespace UpdaterComponents.Tasks
{
    public class UpdateInstaller : ITask
    {

        private string _Message;

        public UpdateInstaller()
        {
            _Message = "Updating the package";
        }

        #region ITask Members

        public string Message
        {
            get { return _Message; }
            set { _Message = value; }
        }

        public void DoTask()
        {            
            ApplyUpdates();

        }


        public void RollBack()
        {
            
            string sUpdatesFile = ConfigurationManager.AppSettings["ReleasesXmlFile"];

            File.AppendAllText("UpgradeLog.txt", "Failed during Applying updates \n");

            string sCurrDir = Directory.GetCurrentDirectory();
            string sDrive = Path.GetPathRoot(sCurrDir);
            string sAppName = ConfigurationManager.AppSettings["ApplicationName"];
            string sDest = sCurrDir;
            string sSource = sDrive + "BackUp";

            //Restore from the backup
            CommonMethods.CopyData(sSource, sDest);
            File.AppendAllText("UpgradeLog.txt", "Backup restored \n");

            if (Directory.Exists(BackUpCreator.BackUpFolderName))
                Directory.Delete(BackUpCreator.BackUpFolderName, true);

            //Delete the NewRelase folder if prsesent
            if (Directory.Exists("NewRelease"))
                Directory.Delete("NewRelease", true);

            if (File.Exists(sUpdatesFile))
                File.Delete(sUpdatesFile);
        }

        #endregion

        private bool ApplyUpdates()
        {
            

            string sAppName = ConfigurationManager.AppSettings["ApplicationName"];
            string sDest = Directory.GetCurrentDirectory();
            string sDrive = Path.GetPathRoot(sDest);
            string sSource = Directory.GetCurrentDirectory() + "\\NewRelease";
            
            //Replace the existing version
            return CommonMethods.CopyData(sSource, sDest);
        }
    }
}
